from fastapi import FastAPI, Request, Response
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST
import time

app = FastAPI()

# 创建Prometheus指标
REQUEST_COUNT = Counter(
    "http_requests_total", 
    "Total HTTP Requests Count", 
    ["app_name", "method", "endpoint", "http_status"]
)
REQUEST_LATENCY = Histogram(
    "http_request_duration_seconds", 
    "HTTP Request Latency", 
    ["app_name", "method", "endpoint"]
)

@app.middleware("http")
async def monitor_requests(request: Request, call_next):
    # 记录请求开始时间
    start_time = time.time()
    
    # 处理请求
    response = await call_next(request)
    
    # 计算请求处理时间
    duration = time.time() - start_time
    
    # 记录指标
    REQUEST_COUNT.labels(
        "fastapi_app", 
        request.method, 
        request.url.path, 
        response.status_code
    ).inc()
    
    REQUEST_LATENCY.labels(
        "fastapi_app", 
        request.method, 
        request.url.path
    ).observe(duration)
    
    return response

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.get("/metrics")
async def metrics():
    return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)